package com.ycsj.goldmedalnewconcept.common.adapter;

import android.app.Service;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.toast.ToastUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.activity.AnswerListDetailsActivity;
import com.ycsj.goldmedalnewconcept.common.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.common.iflytek.Result;
import com.ycsj.goldmedalnewconcept.common.iflytek.XmlResultParser;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 课文跟读详情里列表的适配器
 * Created by Administrator on 2019/4/8 0008.
 */

public class ClassListAdapter extends BaseQuickAdapter<AnswerInfo, BaseViewHolder> {
    private final Context context;

    private final List<AnswerInfo> datas;

    // 录音的弹框PopUpWinow相关
    private View view;
    private ImageView lvPopRecord;
    private PopupWindow popupWindow;
    // 帧动画对象
    private AnimationDrawable animationDrawable;
    private AnimationDrawable newAnimationDrawable;

    // 讯飞SDK对象
    private SpeechEvaluator mSpeechEvaluator;

    // 控制松手是否显示加载框的标记
    private boolean flag = true;
    private final AnswerListDetailsActivity activity;

    public ClassListAdapter(Context context, int layoutResId, @Nullable List<AnswerInfo> data) {
        super(layoutResId, data);
        this.context = context;
        this.activity = (AnswerListDetailsActivity) context;
        //配置科大讯飞
        setParams(context);
        this.datas = data;
    }

    @Override
    protected void convert(final BaseViewHolder holder, final AnswerInfo info) {

        // 获取题目
        TextView tvContent = holder.getView(R.id.tv_topic);

        tvContent.setText(info.questionContent);

        // 顶部的线性布局
        LinearLayout llTopPlay = holder.getView(R.id.ll_top_play);

        // 顶部的喇叭和播放图片
        final ImageView lvTopLaBa = holder.getView(R.id.lv_top_laba);
        AnimationDrawable currDrawable = (AnimationDrawable) lvTopLaBa.getDrawable();
        if (info.isPlayUrl) {
            currDrawable.start();
        } else {
            currDrawable.stop();
        }

        // 播放录音按钮
        final ImageView lvPlay = holder.getView(R.id.lv_replay);

        // 录音按钮
        final ImageView lvRecord = holder.getView(R.id.lvrecord);

        // 加载框
        LinearLayout llLoading = holder.getView(R.id.ll_loading);

        // 记录分数的TextView
        TextView tvScore = holder.getView(R.id.tv_score);

        float b = (float) (Math.round(info.score * 10)) / 10;
        tvScore.setText(b + " 分");

        // 根据状态配置显示状态
        if (info.isPlay) {
            // 是否播放状态
            lvPlay.setImageResource(R.drawable.stopcloze);
        } else {
            lvPlay.setImageResource(R.drawable.playcloze);
        }

        // 控制显示分数的状态
        if (info.isShowScore) {
            // 是否显示分数
            tvScore.setVisibility(View.VISIBLE);
        } else {
            tvScore.setVisibility(View.INVISIBLE);
        }

        // 控制是否显示加载框的状态
        if (info.isShowDialog) {
            // 是否需要显示加载框的状态值
            llLoading.setVisibility(View.VISIBLE);
        } else {
            llLoading.setVisibility(View.INVISIBLE);
        }


        // 顶部播放课文按钮的事件
        llTopPlay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int pos = holder.getAdapterPosition();
                final AnswerInfo currInfo = datas.get(pos);

                // 获取录音文件的地址
                if (!currInfo.isPlayUrl && !TextUtils.isEmpty(currInfo.path)) {

                    // 同步状态
                    // 让其它条目的播放按钮变成停止状态
                    for (int i = 0; i < datas.size(); i++) {
                        if (datas.get(i).isPlay) {
                            datas.get(i).isPlay = false;
                        }
                    }

                    for (int i = 0; i < datas.size(); i++) {
                        if (currInfo != datas.get(i)) {
                            datas.get(i).isPlayUrl = false;
                        } else {
                            currInfo.isPlayUrl = true;
                        }
                    }


                    notifyDataSetChanged();

                    //播放课文音频
                    MediaPlayerManager.getInstance().play(currInfo.path, new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {

                            // 改变图标
                            currInfo.isPlayUrl = false;

                            notifyDataSetChanged();

                            MediaPlayerManager.getInstance().stop();

                        }
                    }, new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {

                            // 改变图标
                            currInfo.isPlayUrl = false;

                            notifyDataSetChanged();

                            MediaPlayerManager.getInstance().stop();

                            return false;
                        }
                    });

                }
            }
        });


        // 录音按钮的录音事件
        lvRecord.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

//                LogUtils.iTag("test", "当前对象是" + info);

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        // 按下的时候重置加载框的状态,加载框和分数都不显示
                        info.isShowDialog = false;
                        info.isShowScore = false;
                        notifyDataSetChanged();

                        // 弹框操作
                        showRecordPop();

                        //重置播放状态
                        for (int i = 0; i < datas
                                .size(); i++) {
                            datas.get(i).isPlay = false;
                            datas.get(i).isPlayUrl = false;
                        }

                        // 通知适配器刷新
                        notifyDataSetChanged();

                        // 释放播放器对象
                        MediaPlayerManager.getInstance().stop();

                        // 录音的操作
                        // 获取Vibrate震动对象
                        Vibrator vibrator = (Vibrator) context
                                .getSystemService(Service.VIBRATOR_SERVICE);
                        vibrator.vibrate(500);

                        if (null != mSpeechEvaluator) {

                            // 重新配置存储位置
                            setAudioPath(info.postion);

                            // 评测功能
                            mSpeechEvaluator.startEvaluating(info.questionContent,
                                    null, new EvaluatorListener() {

                                        // volume音量值0~30，data音频数据
                                        @Override
                                        public void onVolumeChanged(int volume,
                                                                    byte[] data) {

                                        }

                                        // 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
                                        @Override
                                        public void onResult(
                                                EvaluatorResult result,
                                                boolean isLast) {
                                            if (isLast) {

                                                //关闭弹框
                                                PopUpManager.dismiss();

                                                StringBuilder builder = new StringBuilder();
                                                builder.append(result
                                                        .getResultString());

                                                XmlResultParser resultParser = new XmlResultParser();
                                                Result result1 = resultParser
                                                        .parse(result
                                                                .getResultString());

                                                if (!TextUtils.isEmpty(builder)) {

                                                    if (!result1.is_rejected) {
                                                        float a = result1.total_score;
                                                        float b = (float) (Math
                                                                .round(a * 10)) / 10;
                                                        flag = false;

                                                        // 重新设置分数
                                                        info.score = b;
                                                        // 显示分数的TextView
                                                        info.isShowScore = true;
                                                        // 隐藏加载框
                                                        info.isShowDialog = false;
                                                        // 重新配置录音地址
                                                        info.audioPath = getAmrPath(info.postion);

                                                        // 重置状态
                                                        for (int i = 0; i < datas
                                                                .size(); i++) {
                                                            datas.get(i).isPlay = false;
                                                        }

                                                        // 通知适配器刷新
                                                        notifyDataSetChanged();


                                                        //回调已经录音的结果
                                                        if (listener != null) {
                                                            listener.onRecord();
                                                        }

                                                        // 播放科大讯飞的评分播放对应语音
                                                        // 播放科大讯飞的评分语音
                                                        int resId = -1;
                                                        if (b < 1.0) {
                                                            resId = R.raw.musicrecord1;
                                                        } else if (b >= 1.0 && b < 2.0) {
                                                            resId = R.raw.musicrecord2;
                                                        } else if (b >= 2.0 && b < 3.0) {
                                                            resId = R.raw.musicrecord3;
                                                        } else if (b >= 3.0 && b < 4.0) {
                                                            resId = R.raw.musicrecord4;
                                                        } else if (b >= 4.0 && b <= 5.0) {
                                                            resId = R.raw.musicrecord5;
                                                        }

                                                        MediaPlayerManager.getInstance().playLocalFile(resId, null, null);
                                                    } else {

                                                        flag = false;

                                                        // 重新设置分数
                                                        info.score = 0;

                                                        // 显示分数的TextView
                                                        info.isShowScore = true;

                                                        // 隐藏加载框
                                                        info.isShowDialog = false;

                                                        // 重新配置录音地址
                                                        info.audioPath = getAmrPath(info.postion);

                                                        // 重置状态
                                                        for (int i = 0; i < datas
                                                                .size(); i++) {
                                                            datas.get(i).isPlay = false;
                                                        }

                                                        // 通知适配器刷新
                                                        notifyDataSetChanged();

                                                        ToastUtils.show("未检测到录音或者乱读,请重新录音");

                                                    }
                                                }
                                            }
                                        }

                                        // 扩展接口，暂时没有回调
                                        @Override
                                        public void onEvent(int arg0, int arg1,
                                                            int arg2, Bundle arg3) {

                                        }

                                        // 出错回调
                                        @Override
                                        public void onError(SpeechError error) {

                                            // 如果出错关闭PopUpWindow
                                            PopUpManager.dismiss();

                                            flag = false;

                                            // 重置状态
                                            for (int i = 0; i < datas.size(); i++) {
                                                datas.get(i).isPlay = false;
                                            }

                                            // 隐藏加载框显示评分框
                                            info.isShowScore = true;
                                            info.isShowDialog = false;
                                            notifyDataSetChanged();
                                            ToastUtils.show("未检测到录音。。。");
                                        }

                                        // 说话结束回调
                                        @Override
                                        public void onEndOfSpeech() {

                                        }

                                        // 开始说话回调
                                        @Override
                                        public void onBeginOfSpeech() {

                                        }
                                    });
                        }

                        break;

                    case MotionEvent.ACTION_UP:

                        // 松下的操作
                        PopUpManager.dismiss();

                        // 松手的时候开始加载框转圈功能
                        info.isShowDialog = true;
                        info.isShowScore = false;
                        notifyDataSetChanged();

                        break;
                }

                return true;
            }
        });


        // 播放录音文件的点击事件
        lvPlay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //获取点击位置
                int postion = holder.getAdapterPosition();

                final AnswerInfo currInfo = datas.get(postion);

                // 获取录音文件的地址
                if (!currInfo.isPlay && !TextUtils.isEmpty(currInfo.audioPath)) {

                    // 同步状态
                    currInfo.isPlay = true;

                    // 让其它条目的播放按钮变成停止状态
                    for (int i = 0; i < datas.size(); i++) {
                        if (datas.get(i).isPlayUrl) {
                            datas.get(i).isPlayUrl = false;
                        }
                        if (currInfo != datas.get(i)) {
                            datas.get(i).isPlay = false;
                        }
                    }

                    notifyDataSetChanged();

                    // 创建音频播放对象
                    MediaPlayerManager.getInstance().play(currInfo.audioPath, new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {
                            // 改变图标
                            currInfo.isPlay = false;
                            notifyDataSetChanged();
                        }
                    }, new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                            // 改变图标
                            currInfo.isPlay = false;
                            notifyDataSetChanged();
                            return false;
                        }
                    });

                } else {
                    ToastUtils.show("请先录音");
                }
            }
        });

    }


    /**
     * 设置讯飞语音录制对象的参数方法
     */
    private void setParams(Context context) {

        mSpeechEvaluator = SpeechEvaluator.createEvaluator(context, null);

        // 设置评测语种
        mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");
        // 设置评测题型
        // mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
        // "read_word");
        mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
                "read_sentence");
        // 设置试题编码类型
        mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
        // 设置前、后端点超时
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "5000");
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");
        // 设置录音超时，设置成-1 则无超时限制
        mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");
        // 设置结果等级，不同等级对应不同的详细程度
        mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
    }


    /**
     * 单独配置讯飞存放录音文件的方法
     *
     * @param postion
     */
    private void setAudioPath(int postion) {
        // 配置录音文件存放的位置
//        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
//                Environment.getExternalStorageDirectory().getAbsolutePath()
//                        + "/msc/" + "ice" + postion + ".wav");

        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
                this.getAmrPath(postion)
        );
    }


    /**
     * 根据当前页面获取录音文件的路径的方法
     *
     * @return
     */
    private String getAmrPath(int postion) {
//        File file = new File(Environment.getExternalStorageDirectory()
//                .getAbsolutePath() + "/msc/" + "ice" + postion + ".wav");
//        return file.getAbsolutePath();

        File file = new File(this.context.getCacheDir(), "/msc/" + "ice" + postion + ".wav");
        return file.getAbsolutePath();
    }


    /**
     * 弹出录音的PopUpwindow
     */
    private void showRecordPop() {
//        view = View.inflate(context, R.layout.st_pop_record, null);
//        lvPopRecord = view.findViewById(R.id.lv_pop_record);
//
//        // 给顶部的图片设置帧动画
//        lvPopRecord.setImageResource(R.drawable.st_record_anim);
//
//        // 获取帧动画对象
//        animationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();
//
//        // 开启帧动画
//        animationDrawable.start();
//
//        popupWindow = new PopupWindow(view,
//                WindowManager.LayoutParams.WRAP_CONTENT,
//                WindowManager.LayoutParams.WRAP_CONTENT);
//
//        popupWindow.setFocusable(true);
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//
//        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//
//            @Override
//            public void onDismiss() {
//                if (null != animationDrawable) {
//                    animationDrawable.stop();
//                }
//            }
//        });
//
//        popupWindow.showAtLocation(activity.getWindow().getDecorView(),
//                Gravity.CENTER, 0, 0);


        PopUpManager.showPop(context, R.layout.item_record_pop, 0.3f, activity, null);
    }


    /**
     * 回调接口,用于是否界面重新录音的监听
     */
    public interface onRecordListener {
        void onRecord();
    }

    private onRecordListener listener;

    public void setListener(onRecordListener listener) {
        this.listener = listener;
    }
}
